import { observable, action, autorun } from 'mobx';
import API from '../../apis';

class TreeStore {
    @observable
    state = {
        init: {
            datas: [],
            suffixs: [],
        }
    }
    @action
    update = (modeId, info) => {
        this.state = {
            ...this.state,
            [modeId]: {
                ...this.getState(guid),
                ...info
            }
        }
    }
    @action
    updateDatas = (guid, datas, parentkey) => {
        const _state = this.getState(guid);
        const olddatas = _state.datas;
        let newdatas;
        if (olddatas.length == 0) {
            newdatas = datas;
        } else {
            newdatas = olddatas.map(d => {
                if (d.key == parentkey) {
                    return {
                        ...d,
                        children: datas
                    }
                } else {
                    return {
                        ...d
                    }
                }
            })
        }
        this.state = {
            ...this.state,
            [guid]: {
                ..._state,
                datas: newdatas
            }
        };
    }
    datas = (params = {}) => {
        const { guid, parentkey, resolve } = params;
        API.Tree.datas({ guid, parentkey }).then(({ datas, api_errormsg, api_status }) => {
            if (api_status) {
                this.updateDatas(guid, datas, parentkey)
            } else {
                console.log(api_errormsg);
                throw api_errormsg;
            }
            resolve();
        })
    }
    getState = (guid) => {
        if (guid in this.state) {
            return this.state[guid];
        } else {
            return this.state.init;
        }
    }
}

export default new TreeStore();